﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using Common.Logging;
using WuDada.Trade.DataLoader.Domain;
using WuDada.Utility;
using CsQuery;
using WuDada.Trade.DataLoader.Utility;
using WuDada.Core.SystemApplications;
using WuDada.Trade.DataLoader.Service;

public partial class googleStock : System.Web.UI.Page
{
    private ILog m_Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private TradeDataLoaderFactory m_TradeDataLoaderFactory = new TradeDataLoaderFactory();
    private IDataLoadService m_DataLoadService;
    protected string period;
    protected string stockCode;
    protected string startYear;
    protected string startMonth;
    protected string startDay;
    protected string endYear;
    protected string endMonth;
    protected string endDay;
    protected string pageNum;
    protected string dataStartIndex;

    protected void Page_Load(object sender, EventArgs e)
    {
        m_DataLoadService = m_TradeDataLoaderFactory.GetDataLoadService();

        if (!IsPostBack)
        {
            InitParam();
            ChecParam();
            GenStockData();
        }
    }

    private void ChecParam()
    {
        stockCode = "TPE:3702";
        //if (string.IsNullOrEmpty(stockCode) || string.IsNullOrEmpty(startYear) || string.IsNullOrEmpty(startMonth)
        //    || string.IsNullOrEmpty(startDay) || string.IsNullOrEmpty(endYear) || string.IsNullOrEmpty(endMonth)
        //    || string.IsNullOrEmpty(endDay) || string.IsNullOrEmpty(dataStartIndex))
        //{
        //    throw new Exception("傳入的參數錯誤");
        //}
    }

    private void InitParam()
    {
        stockCode = QueryStringHelper.GetString("stockCode", string.Empty);
        period = QueryStringHelper.GetString("period", StockDataVO.StockDataPeriod.Day.ToString());
        startYear = QueryStringHelper.GetString("startYear", string.Empty);
        startMonth = QueryStringHelper.GetString("startMonth", string.Empty);
        startDay = QueryStringHelper.GetString("startDay", string.Empty);
        endYear = QueryStringHelper.GetString("endYear", string.Empty);
        endMonth = QueryStringHelper.GetString("endMonth", string.Empty);
        endDay = QueryStringHelper.GetString("endDay", string.Empty);
        pageNum = QueryStringHelper.GetString("pageNum", "30");
        dataStartIndex = QueryStringHelper.GetString("dataStartIndex", string.Empty);
    }

    private void GenStockData()
    {
        string url = "http://www.google.com/finance/historical?q=TPE:3702&startdate=Jan+1%2C+2000&enddate=Aug+29%2C+2012&num=200&start=0";
        //string url = string.Format("http://www.google.com/finance/historical?q={0}&startdate={1}+{2}%2C+{3}&enddate={4}+{5}%2C+{6}&num={7}&start={8}"
        //    , stockCode, startMonth, startDay, startYear, endMonth, endDay, endYear, pageNum, dataStartIndex);

        string result = Get(url);
        //m_Log.Debug(result);
        int startIndex = result.IndexOf("<div id=prices");
        int endIndex = result.LastIndexOf("</form>");
        //m_Log.Debug("startIndex = " + startIndex);
        //m_Log.Debug("endIndex = " + endIndex);
        if (startIndex != -1)
        {
            string content = result.Substring(startIndex, (endIndex - startIndex));
            //m_Log.Debug(content);
            //ltlContent.Text = content;

            CQ doc = CQ.Create(content);
            CQ trCQ = doc.Select(".historical_price tr");
            for (int i = 0; i < trCQ.Count(); i++)
            {
                //跳過第一個Title
                if (i != 0)
                {
                    IDomObject tdDoms = trCQ[i];

                    string date = string.Empty;
                    double open = 0.0;
                    double high = 0.0;
                    double low = 0.0;
                    double close = 0.0;
                    string volume = string.Empty;

                    date = tdDoms.ChildElements.ElementAt(0).InnerText;
                    try
                    {
                        open = double.Parse(tdDoms.ChildElements.ElementAt(1).InnerText);
                    }
                    catch
                    {
                    }
                    try
                    {
                        high = double.Parse(tdDoms.ChildElements.ElementAt(2).InnerText);
                    }
                    catch
                    {
                    }
                    try
                    {
                        low = double.Parse(tdDoms.ChildElements.ElementAt(3).InnerText);
                    }
                    catch
                    {
                    }
                    try
                    {
                        close = double.Parse(tdDoms.ChildElements.ElementAt(4).InnerText);
                    }
                    catch
                    {
                    }
                    volume = tdDoms.ChildElements.ElementAt(5).InnerText;

                    CreateStockData(date, open, high, low, close, volume);
                }
            }
        }
    }

    private void CreateStockData(string strDataTime, double openValue
        , double highValue, double lowValue, double closeValue, string strVolume)
    {
        try
        {
            int volume = int.Parse(strVolume.Replace(",", ""));
            DateTime dataTime = GoogleStockDataConvertUtil.ToDateTime(strDataTime);

            //先判斷該筆資料是否有建立過
            if (m_DataLoadService.GetStockData(stockCode, dataTime) != null)
            {
                m_Log.Debug(string.Format("{0} exist.", stockCode));
            }
            else
            {
                StockDataVO stockDataVO = new StockDataVO();
                stockDataVO.StockCode = stockCode;
                stockDataVO.Period = (StockDataVO.StockDataPeriod)Enum.Parse(typeof(StockDataVO.StockDataPeriod), period);
                stockDataVO.DataTime = dataTime;
                stockDataVO.OpenValue = openValue;
                stockDataVO.HighValue = highValue;
                stockDataVO.LowValue = lowValue;
                stockDataVO.CloseValue = closeValue;
                stockDataVO.Volume = volume;

                stockDataVO = m_DataLoadService.CreateStockData(stockDataVO);
                m_Log.Debug(string.Format("{0}, {1} ok.", stockCode, strDataTime));
            }


        }
        catch (Exception ex)
        {
            m_Log.Error(ex);
        }
    }

    private string Get(string url)
    {
        m_Log.Debug("url = " + url);
        WebClient c = new WebClient();
        byte[] response = c.DownloadData(url);
        return Encoding.UTF8.GetString(response);
    }
}